import React from 'react';
import s from './index.less';
import compression from './imgCompression';

const stys = {
    wrapper: {
        display: 'inline-block',
        position: 'relative',
    },
    del: {
        display: 'inline-block',
        width: 20,
        height: '20px',
        position: 'absolute',
        top: '-8px',
        right: '6px',
        textAlign: 'center',
        lienHeight: '20px',
        color: '#f40',
        fontWeight: '700',
        cursor: 'pointer',
    }
};

class ImageUpload extends React.Component {

    addFile = async e => {
        const { setFile, imgs } = this.props;
        console.log('el', e);
        const files = this.input.files;
        const igs = imgs.concat();
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            const blob = await compression(file, { width: 720, mimeType: 'image/jpeg', quality: 1 });
            blob.name = file.name;
            const src = URL.createObjectURL(blob);
            igs.push({ src, blob });
        }
        setFile(igs);
        document.querySelector('#workOrderInput').value = '';
    }

    click = () => {
        const { disabled } = this.props;
        if (disabled) return;
        this.input.click();
    }

    remove = (i) => {
        // console.log('this.input.files', this.input.files);
        typeof this.props.remove === 'function' && this.props.remove(i);
    }

    render() {
        const inputProps = {
            accept: 'image/*',
            capture: 'camera'
        };

        const { imgs, remove } = this.props;
        return (
            <div>
                {
                    imgs.map((img, i) => (
                        <div style={stys.wrapper}>
                            <img
                                src={img.src}
                                className={s.img}
                                key={img.src}
                            // onClick={() => this.setState({ showDetail: img.src })}
                            />
                            {remove && <span style={stys.del} onClick={() => this.remove(i)}>X</span>}
                        </div>)
                    )
                }
                {
                    imgs.length < 5 ? <div className={s.img} onClick={this.click}>
                        <span>+</span>
                        <div>点击上传相关图片</div>
                        <input id="workOrderInput" type="file" ref={d => this.input = d} onChange={this.addFile} multiple {...inputProps} />
                    </div> : null
                }
            </div>
        );
    }
}

export default ImageUpload;
